export function Pubguru(html) {
    const result = { ...html };
    const hostname = html.hostname;

    const ad1Mapping = ['detailtop4', 'detailmiddle5'];
    const ad2Mapping = [];

    let homeBottomCounter = 0;

    const adKeys = Object.keys(result)
        .filter(k => k.startsWith('ad'))
        .sort((a, b) => {
            const [pA, iA] = a.split('_');
            const [pB, iB] = b.split('_');
            if (pA === pB) return Number(iA) - Number(iB);
            return pA.localeCompare(pB);
        });

    for (const key of adKeys) {
        const prefix = key.split("_")[0];
        let slotName = "";

        if (prefix === "ad0") {
            if (homeBottomCounter === 0) slotName = "hometop1";
            else if (homeBottomCounter === 1) slotName = "homemiddle2";
            else slotName = `homebottom3-${homeBottomCounter - 2}`;
            homeBottomCounter++;
        } else if (prefix === "ad1") {
            slotName = ad1Mapping.shift();
        } else if (prefix === "ad2") {
            slotName = ad2Mapping.shift();
        }

        if (slotName) {
            const isIndexZero = /^ad\d+_0$/.test(key);
            const dataAttr = isIndexZero ? ' data-ad-index="0"' : "";

            result[key] = `
                <div class="ad-container"${dataAttr}>
                  <div class='gptslot'>
                    <pubguru data-pg-ad="${hostname}_${slotName}"></pubguru>
                  </div>
                </div>`;
        }
    }

    const gptScript = `<script type="text/javascript" async src="//c.pubguru.net/pg.${hostname}.js"></script>` +
        (result.htmlTest ? `\n${result.htmlTest}` : '');

    result.htmlTest = gptScript.trim();
    return result;
}


Pubguru.exampleForm = {
    host: 'www.pubguru.com',
    dirpath: 'example',
    html: {
        htmlTest: ``,
        hd_index: ``,
        hd_details: ``,
        hd_category: ``,
        hd_play: ``,
        ad0_0: `<pubguru data-pg-ad="sda_hometop1"></pubguru>`,
        ad0_1: `<pubguru data-pg-ad="sda_homemiddle2"></pubguru>`,
        ad0_2: `<pubguru data-pg-ad="sda_homebottom3-0"></pubguru>`,
        ad0_3: `<pubguru data-pg-ad="sda_homebottom3-1"></pubguru>`,
        ad1_0: `<pubguru data-pg-ad="sda_detailtop4"></pubguru>`,
        ad1_1: `<pubguru data-pg-ad="sda_detailmiddle5"></pubguru>`,
        interstitial: ``,
        anchor: ``,
    }
}

export function parsePubguruCode(rawInputString) {
    const match = rawInputString.match(/pg\.([a-zA-Z0-9_-]+)\.js/);
    return {
        type: 'pubguru',
        items: {
            hostname: match ? match[1] : ''
        }
    };
}
